import { Injectable, NotFoundException } from "@nestjs/common";

import { OutputsService } from "../outputs/outputs.service";
import { PrismaService } from "../prisma/prisma.service";

@Injectable()
export class ProjectsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly outputsService: OutputsService,
  ) {}

  async findAll() {
    const projects = await this.prisma.project.findMany({
      orderBy: {
        name: "asc",
      },
    });

    return Promise.all(
      projects.map(async (project) => {
        const metrics = await this.outputsService.getProjectMetrics(project.id);
        const currentValue = metrics.month;
        const progressPercentage =
          project.monthlyTarget && project.monthlyTarget > 0
            ? Math.round((currentValue / project.monthlyTarget) * 100)
            : null;

        return {
          id: project.id,
          name: project.name,
          description: project.description,
          managerName: project.managerName,
          monthlyTarget: project.monthlyTarget,
          currentValue,
          progressPercentage,
          metrics,
        };
      }),
    );
  }

  async findOne(id: string) {
    const project = await this.prisma.project.findUnique({
      where: { id },
      select: {
        id: true,
        name: true,
        description: true,
        managerName: true,
        monthlyTarget: true,
        isActive: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    if (!project) {
      throw new NotFoundException("Project not found");
    }

    const [metrics, recentOutputs] = await Promise.all([
      this.outputsService.getProjectMetrics(project.id),
      this.outputsService.findRecentByProject(project.id, 20),
    ]);

    const currentValue = metrics.month;
    const progressPercentage =
      project.monthlyTarget && project.monthlyTarget > 0
        ? Math.round((currentValue / project.monthlyTarget) * 100)
        : null;

    return {
      ...project,
      currentValue,
      progressPercentage,
      metrics,
      recentOutputs,
    };
  }
}
